//
//  IssueDetialTableViewCell.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/26.
//

import UIKit
import MarkdownView
import Kingfisher
import WebKit
import SnapKit
import PKHUD

/// issue的详细信息展示cell
class IssueDetialTableViewCell: UITableViewCell {
    
    
    @IBOutlet weak var issueTitleLabel: UILabel!
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var createdDateLabel: UILabel!
    
    @IBOutlet weak var issueDescView: UIView!
    
    var webView:WKWebView!
    
    var model:IssueModel?{
        didSet{
            guard let m = model,let autor = m.author else {
                getUserInfo(userid: model!.author_id)
                return
            }
            
            if let icon = URL(string: autor.portrait_url!) {
                userImageView.kf.setImage(with: icon, placeholder: UIImage(named: "image_loading"), options: .none, progressBlock: nil, completionHandler: nil)
            }
            
            issueTitleLabel.text = m.title
            userNameLabel.text = m.author.name
            createdDateLabel.text = "创建于 \(m.created_at.intervalSinceNow())"
            
            webView.loadHTMLString(m.description!, baseURL: nil)
            
        }
    }
    
    func getUserInfo(userid:Int){
        
        let url = URLs.V3URL + "users/" + userid.description
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<UserModel> = NetWorkTool.shared.getRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    var temp = self.model
                    temp?.author = result.data
                    self.model = temp
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
            }
        }
        
    }
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        if #available(iOS 13.0, *) {
            self.contentView.backgroundColor = Colors.backgroundColor
            issueTitleLabel.textColor = Colors.labelColor
        } else {
            self.contentView.backgroundColor = .white
            issueTitleLabel.textColor = .black
        }
        
        var bounds = self.userImageView.bounds
        bounds.size.height -= 4
        bounds.size.width -= 4
        bounds.origin.x += 1
        bounds.origin.y += 1
        // Add rounded corners
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds//self.AutorImageView.bounds
        maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 20).cgPath
        self.userImageView.layer.mask = maskLayer
        
        // Add border
        let borderLayer = CAShapeLayer()
        borderLayer.path = maskLayer.path // Reuse the Bezier path
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = UIColor.lightGray.cgColor
        borderLayer.lineWidth = 0.5
        borderLayer.frame = bounds
        self.userImageView.layer.addSublayer(borderLayer)
        
        
        let wkWebConfig = WKWebViewConfiguration()
        // 自适应屏幕宽度js
        let jSString = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
        let wkUserScript = WKUserScript(source: jSString, injectionTime: .atDocumentEnd, forMainFrameOnly: true)

        // 添加自适应屏幕宽度js调用的方法
        let wkUserController = WKUserContentController()
        wkUserController.addUserScript(wkUserScript)

        wkWebConfig.userContentController = wkUserController
        webView = WKWebView(frame: contentView.bounds, configuration: wkWebConfig)
        issueDescView.addSubview(webView)
        webView.navigationDelegate = self
        webView.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalToSuperview()
        }
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}

// MARK: - 加载完成后 设置webview 的背景颜色 适配暗色模式
extension IssueDetialTableViewCell:WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        if #available(iOS 13.0, *) {
            if UITraitCollection.current.userInterfaceStyle == .dark {
                webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.background='#5e5e5e'", completionHandler: nil)
            }else {
                webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.background='#ffffff'", completionHandler: nil)
            }
        }
    }
}
